import VueRouter from 'vue-router'
import axios from 'axios'
import store from '@/store'
import { baseUrl } from '@/config'

const TokenRefreshKey = 'Login-Refresh'
const LogoUrlKey = 'logo-url'


export function setUserInfo (data){
	localStorage.setItem(UserInfoKey, JSON.stringify(data))
}


export function setRefreshLoginToken(token){
	localStorage.setItem(TokenRefreshKey, token)
}

export function getRefreshLoginToken(){
	return localStorage.getItem(TokenRefreshKey)
}

export function setLogoUrl(url){
	return localStorage.setItem(LogoUrlKey, url)
}

export function getLogoUrl(){
	return localStorage.getItem(LogoUrlKey)
}

export function removeLogoUrl(){
	return localStorage.removeItem(LogoUrlKey)
}

let ISFRESHLOGINTOKEN = false
let refreshTimerTimeOut = null


export class Request{
	constructor() {
			this.parseResult = true
			this.taskListInter = null
			this.isRefreshLoginIng = false
			this.isSendIng = false
			this.isMany = false
			this.taskList = []
			
			this.axios = axios.create({
				//baseURL : process.env.NODE_ENV === 'development' ? '' : baseUrl,
				timeout : 60000,
				headers : {
					post : {
						'Content-Type' : 'application/json'
					}
				}
			})

			
			/* axios.defaults.baseURL = baseUrl
			axios.defaults.timeout = 60000
			axios.defaults.headers.post['Content-Type'] = 'application/json' */
			this.config = {
				params : {},
				data : {}
			}
	}

	setParseResult (parseResult) {
		this.parseResult = parseResult
	}

	setBaseURL(baseUrl){
		this.config.baseURL = baseUrl
	}

	setConfig(key, value){
		this.config[key] = value
	}

	setMany(flag = true){
		this.isMany = flag
	}

	addTask(url, callback, data, method = 'get'){
		console.log('addTask')
		this.taskList.push({url : url, data : data, callback : callback, method : method.toLowerCase()})
	}

	task(){
		let task = this.taskList.shift()
		if(!task){
			return
		}
		this[task.method](task.url, res => {
			task.callback(res)
			
		}, task.data)
	}

	params (params) {
		this.config.params = Object.assign(this.config.params, params)
		return this
	}

	post(url,callback,data = {}){
		this.config.method = 'POST'
		this.config.data = data
		this.send(url, callback, data)
	}

	get(url,callback,params = {}){
		this.config.method = 'GET'
		this.config.params = params
		this.send(url, callback, params)
	}

	put(url,callback,data = {}){
		this.config.method = 'PUT'
		this.config.data = data
		this.send(url, callback, data)
	}
	
	delete(url,callback,data = {}){
		this.config.method = 'DELETE'
		this.config.data = data
		this.send(url, callback, data)
	}


  send(url, callback, data){
    if (this.isSendIng && !this.isMany) return
		this.config.headers = {}
    let token = store.state.loginToken
    if(token){
      this.config.headers.Authorization = token
			
    }

		
    this.isSendIng = true
    this.config.url = url
		this.axios.request(this.config).then(response => {
			this.isSendIng = false
			let repdata = response.data

			if(this.parseResult == true) {
				let codeArr = [1, 5, 6, 8]
				if(codeArr.includes(repdata.code)){
					location.hash = '#/login'
					return
				}

				repdata.success = repdata.code == 0 ? true : false
			}

			callback(repdata)

		
		})
		.catch(e => {
			this.isSendIng = false
			console.log(e)
			let msg = '网络错误'
			if(e.response.data){
				let codeArr = [1, 5, 6, 8]
				if(codeArr.includes(e.response.data.code)){
					location.hash = '#/login'
					return
				}
				msg = e.response.data.message || e.response.data.msg
			}
			callback({code : 500, msg : msg, success : false})
		})
  }

  abort(){

  }
}


export function errorToast(msg, $this){
	 $this.$message({
			showClose: true,
			message: msg,
			type: 'error'
		})
}

export function successToast(msg, $this){
	$this.$message({
		showClose: true,
		message: msg,
		type: 'success'
	})
}

export function confirm(msg = '', callback, title = '系统提示', $this){
	
	this.$confirm(msg, title).then(() => {
		callback()
	})
	
}

export function loading(msg='正在加载', $this){
	return $this.$loading({
		lock: true,
		text: msg,
		spinner: 'el-icon-loading',
		background: 'rgba(0, 0, 0, 0.7)'
	})
}

export function valiMobile(mobile){
  return /^1[3|5|7|9|8]\d{9}$/.test(mobile)
}


export function parseTime(time, cFormat) {
	if(time == 0){
		return ''
	}
	
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    if (key === 'a') return ['一', '二', '三', '四', '五', '六', '日'][value - 1]
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
	
  return time_str
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) { // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分'
  }
}

export function getDate(days = 0){
		let currentDate = new Date()
		let y, m, d = ''
		if(days === 0){
			y = currentDate.getFullYear()
			m = currentDate.getMonth() + 1
			d = currentDate.getDate()
			
		}else{
			let time = currentDate.getTime() + 3600 * 24 * 1000 * days
			let date = new Date(time)
			y = date.getFullYear()
			m = date.getMonth() + 1
			d = date.getDate()

		}
		
		if(m < 10){
			m = '0' + m
		}
		
		if(d < 10){
			d = '0' + d
		}
		
		return `${y}-${m}-${d}`
		
	}
	
	
	export function filterEmptyParam(params){
		let _params = Object.assign({}, params)
		for(let k in _params){
			if(_params[k] === ''){
				delete _params[k]
			}
		}
		
		return _params
	}
	
	
	export function checkPermission(){
		let roles = Array.from(arguments)
		
		let roleTypes = ['admin', 'agent', 'store']
		let role = getUserRole()

		let roleType = roleTypes[role]

		return roles.includes(roleType)
		
	}
	
	
	export function round(num,fixed){
		if(typeof fixed === "undefined"){
			fixed = 2
		}
		num = String(num)
		let nums = num.split(".")
		if(nums[1]){
			nums[1] = nums[1].substr(0,fixed)
			num = nums[0] + "." + nums[1]
		}
		
		return Number(num)
	}


	export function stringToHex(str){
		var val="";
		for(var i = 0; i < str.length; i++){
		if(val == "")
			val = str.charCodeAt(i).toString(16);
		else
			val += "" + str.charCodeAt(i).toString(16);
		}
		if(str.indexOf("-RJ45") > 1){
			val = val.toUpperCase()
		}
		return val
	}